package com.glowdayz.glowmee.bc;

import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.glowdayz.common.DBHandler;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.MultipartBox;
import com.glowdayz.common.MultipartBox.FileInfo;
import com.glowdayz.glowmee.cmd.ProductCMD;
import com.glowdayz.glowmee.cmd.ProductCategoryCMD;
import com.glowdayz.glowmee.dao.BrandDAO;
import com.glowdayz.glowmee.dao.FirstCategoryDAO;
import com.glowdayz.glowmee.dao.ProductDAO;

public class UpdateProductBC extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
    public UpdateProductBC() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DBHandler.getInstance().connect();
		
		request.setCharacterEncoding("utf-8");
		
		int idProduct = Integer.parseInt(request.getParameter("id"));
		int page = 1;
		String pageStr = request.getParameter("page");
		if (pageStr != null) {
			page = Integer.parseInt(pageStr);
		}
		
		int pageCnt = 10;
		String pageCnt_str = request.getParameter("pageCnt");
		if (pageCnt_str != null && !pageCnt_str.equals("")) {
			pageCnt = Integer.parseInt(pageCnt_str);
		}
		
		String where = request.getParameter("where");
		String order = request.getParameter("order");
		
		try {
			ProductCMD cmd = ProductDAO.getInstance().getProduct(idProduct);
			
			request.setAttribute("page", page);
			request.setAttribute("pageCnt", pageCnt);
			if (where != null && !where.equals("")) {
				request.setAttribute("where", "&where=" + where);
			}
			if (order != null && !order.equals("")) {
				request.setAttribute("order", "&order=" + order);
			}
			request.setAttribute("first", FirstCategoryDAO.getInstance().getFirstCategoryList(1, -1, "isDisplay=1"));
			request.setAttribute("brand", BrandDAO.getInstance().getBrandList(1, -1, "brandTitle", "b.isDisplay=1"));
			String keyWord = cmd.getKeyWord();
			if (keyWord != null) {
				String[] keyWord_arr = keyWord.split(",");
				request.setAttribute("keyWord", keyWord_arr);
			}
			request.setAttribute("cmd", cmd);
		} catch (Exception e) {
			DBHandler.getInstance().disconnect();
			e.printStackTrace();
		}
		
		DBHandler.getInstance().disconnect();
		RequestDispatcher dpr = request.getRequestDispatcher("/product/updateProduct.jsp");
		dpr.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DBHandler.getInstance().connect();
		
		request.setCharacterEncoding("utf-8");
		
		MultipartBox mbox = MultipartBox.getInstance();
		
		FileInfo finfo = mbox.upload2(request);
		
		int idProduct = mbox.getInt("id");
		int isDisplay = mbox.getInt("isDisplay");
		String productTitle = mbox.getValue("productTitle");
		int brand = mbox.getInt("brand");
		String[] second = mbox.getValues("second");
		String[] keyWord_arr = mbox.getValues("keyWord");
		String volume = mbox.getValue("volume");
		int price = mbox.getInt("price");
		String colorType = mbox.getValue("colorType");
		if (colorType.equals("")) {
			colorType = null;
		}
		String productText = mbox.getValue("productText");
		int page = mbox.getInt("page");
		int pageCnt = mbox.getInt("pageCnt");
		String where = mbox.getValue("where");
		String order = mbox.getValue("order");
		
		String keyWord = null;
		if (keyWord_arr != null) {
			keyWord = "";
			ArrayList<String> list = new ArrayList<String>();
			for (int i=0; i<keyWord_arr.length; i++) {
				if (!list.contains(keyWord_arr[i])) {
					list.add(keyWord_arr[i]);
				}
			}
			String uniqueKeyWord_arr[] = new String[list.size()];
			list.toArray(uniqueKeyWord_arr);
			for (int i=0; i<uniqueKeyWord_arr.length; i++) {
				if (i+1 == uniqueKeyWord_arr.length) {
					keyWord += uniqueKeyWord_arr[i];
				} else {
					keyWord += uniqueKeyWord_arr[i] + ",";
				}
			}
		}
		
		int[] n_second = new int[second.length];
		for (int i=0; i<second.length; i++) {
			n_second[i] = Integer.parseInt(second[i]);
		}
		
		ArrayList<ProductCategoryCMD> cateList = new ArrayList<ProductCategoryCMD>();
		for (int i=0; i<n_second.length; i++) {
			ProductCategoryCMD cmd = new ProductCategoryCMD(n_second[i]);
			cateList.add(cmd);
		}
		
		try {
			ProductCMD cmd = ProductDAO.getInstance().getProduct(idProduct);
			FileInfo image = cmd.getImage();
			if (image != null && finfo != null) {
				DBHandler.getInstance().beginTrans();
				if (finfo.getFieldName().equals("editImg")) {
					String edit = "UPDATE attachefile SET fileOrgName=?, fileSaveName=?, fileDir=?, fileSize=?, fileType=?, modified_date=? "
							+ "WHERE idAttacheFile=?";
					PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(edit);
					pstmt.setString(1, finfo.getFileOrgName());
					pstmt.setString(2, finfo.getFileSaveName());
					pstmt.setString(3, finfo.getFileDir());
					pstmt.setLong(4, finfo.getFileSize());
					pstmt.setString(5, finfo.getFileType());
					pstmt.setString(6, DateTime.getInstance().getNowDateTimeString());
					pstmt.setInt(7, image.getIdAttacheFile());
					pstmt.executeUpdate();
					pstmt.close();
					pstmt = null;
					finfo = null;
					File f = new File(image.getFileDir() + "/" + image.getFileSaveName());
					if (f.exists()) {
						f.delete();
					}
				}
			}
		} catch (Exception e) {
			DBHandler.getInstance().rollback();
			DBHandler.getInstance().disconnect();
			mbox.deleteFile(finfo);
			e.printStackTrace();
		}
		
		try {
			ProductDAO.getInstance().updateProduct(new ProductCMD(idProduct, brand, productTitle, volume, price, productText,
					colorType, keyWord, isDisplay, finfo), cateList);
		} catch (Exception e) {
			DBHandler.getInstance().rollback();
			DBHandler.getInstance().disconnect();
			mbox.deleteFile(finfo);
			e.printStackTrace();
		}
		
		try {
			ProductCMD cmd = ProductDAO.getInstance().getProduct(idProduct);
			
			int brandTotal = DBHandler.getInstance().getCount("brand", "idBrand", null);
			request.setAttribute("first", FirstCategoryDAO.getInstance().getFirstCategoryList(1, -1, "isDisplay=1"));
			request.setAttribute("brand", BrandDAO.getInstance().getBrandList(1, brandTotal, "brandTitle", "b.isDisplay=1"));
			String keyWordStr = cmd.getKeyWord();
			if (keyWordStr != null) {
				String[] keyWordArr = keyWordStr.split(",");
				request.setAttribute("keyWord", keyWordArr);
			}
			request.setAttribute("cmd", cmd);
			request.setAttribute("alert", "<script type='text/javascript'>alert('수정이 완료되었습니다.');"
					+ "location.replace('listProduct.do?page=" + page + "&pageCnt=" + pageCnt + where + order + "');</script>");
		} catch (Exception e) {
			DBHandler.getInstance().rollback();
			DBHandler.getInstance().disconnect();
			e.printStackTrace();
		}
		
		DBHandler.getInstance().commit();
		DBHandler.getInstance().disconnect();
		RequestDispatcher dpr = request.getRequestDispatcher("/product/updateProduct.jsp");
		dpr.forward(request, response);
	}

}